package com.ruoyi.framework.websocket;

import javax.websocket.ClientEndpoint;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Data
@Slf4j
@ClientEndpoint
public class TbWsClient {
    private Session session;
    private Session downStream;

    @OnOpen
    public void open(Session session) {
        log.info("Client WebSocket is opening...");
        this.session = session;
    }
    
    @OnMessage
    public void onMessage(String message) {
        log.info("Server send message: " + message);
        if (downStream != null) {
            try {
                JSONObject raw = JSON.parseObject(message);
                JSONObject parsed = new JSONObject();
                if (raw.getInteger("errorCode") == 0) {
                    parsed.put("error", false);
                    parsed.put("message", "");
                    JSONObject rawData = raw.getJSONObject("data");
                    JSONObject parsedData = new JSONObject();
                    for (String key : rawData.keySet()) {
                        if (key.equals("latestValues")) {
                            continue;
                        }
                        JSONArray rawValue = rawData.getJSONArray(key);
                        JSONArray firstRawValue = rawValue.getJSONArray(0);
                        parsedData.put(key, firstRawValue.get(1));
                    }
                    parsed.put("data", parsedData);
                } else {
                    parsed.put("error", true);
                    parsed.put("message", raw.get("errorMsg"));
                }
                downStream.getAsyncRemote().sendText(parsed.toJSONString());
            } catch (Exception e) {}
        }
    }
    
    @OnClose
    public void onClose() {
        log.info("Websocket closed");
    }

    public void send(String message) {
        this.session.getAsyncRemote().sendText(message);
    }
}
